//
//  GroupUserListViewController.m
//  Guazi
//
//  Created by koolearn on 11-5-16.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GroupUserListViewController.h"
#import "User.h"
#import "ProfileImageCell.h"
#import "ContactPickerViewController.h"
#import "GuaziAppDelegate.h"
#import "GroupService.h"
#import "FriendsViewController.h"


@interface GroupUserListViewController(private)
- (void) buildBarButtonItem;
@end



@implementation GroupUserListViewController


#pragma mark -
#pragma mark Initialization


- (id) initWithGroup:(FriendGroup*)g
{
    self = [super initWithStyle:UITableViewStylePlain];
	if ( self ) {
		group = [g retain];
		friends = [[NSMutableArray alloc] initWithCapacity:[group.friends count]];
		deletedFriends = [[NSMutableArray alloc] initWithCapacity:0];
		addedFriends = [[NSMutableArray alloc] initWithCapacity:0];
		
		for ( User* user in group.friends ) {
			[friends addObject:user];
		}
	}
	
	return self;
}



#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	[self buildBarButtonItem];
    self.title = @"组联系人列表";
}


- (void) buildBarButtonItem
{
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
                                                                                            target:self 
                                                                                            action:@selector(add)] autorelease];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"返回" 
                                                                             style:UIBarButtonItemStylePlain 
                                                                            target:self action:@selector(finish)] autorelease];
}


- (void) delete:(id)sender
{
	UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:@"是否确认从本组中移除该联系人？移除后，该联系人会加入到未分组中" 
													   delegate:self 
											  cancelButtonTitle:@"取消" 
										 destructiveButtonTitle:@"确定" 
											  otherButtonTitles:nil];
    UIButton* button = (UIButton*)sender;
	sheet.tag = button.tag; //tag is rownumber
	[sheet showInView:[GuaziAppDelegate getAppDelegate].tabBarController.view];
	[sheet release];
}


- (void) didDelete:(long long)userId
{
	NSInteger row = -1;
    for ( int i=0; i<[friends count]; i++) {
        User* user = [friends objectAtIndex:i];
        if ( user.userId == userId ) {
            row = i;
            break;
        }
    }
    
    if ( row == -1 ) return;

	User* user = [friends objectAtIndex:row];
	[friends removeObjectAtIndex:row];
	[deletedFriends addObject:user];
	
    row = -1;
    for ( int i=0; i<[group.friends count]; i++ ) {
        User* u = [group.friends objectAtIndex:i];
        if ( u.userId == user.userId ) {
            row = i;
            break;
        }
    }
    
    if ( row >=0 ) {
        [group.friends removeObjectAtIndex:row];
        group.friendCount = [group.friends count];
    }
    
    [self.tableView reloadData];
	
    [GroupService removeUser:user.userId fromGroup:group.groupId];
}


- (void) add
{
	ContactPickerViewController* controller = [[ContactPickerViewController alloc] initWithDelegate:self action:@selector(didAddUser:)];
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
}


- (void) finish
{
    if ( [deletedFriends count] > 0 || [addedFriends count] > 0 ) {
        FriendsViewController* controller = (FriendsViewController*) [[GuaziAppDelegate getAppDelegate] currentTabRootViewController];
        [controller refreshUsersInGroup:group];
    }
    [self.navigationController popViewControllerAnimated:YES];
}


- (void) didAddUser:(User*)user
{
	for ( User* u in friends ) {
		if ( u.userId == user.userId ) return;
	}
	
	[friends insertObject:user atIndex:0];
    [group.friends insertObject:user atIndex:0];
	[addedFriends addObject:user];
	group.friendCount = [group.friends count];
	
    [GroupService addUser:user toGroup:group.groupId];
    [self.tableView reloadData];
}


#pragma mark Actionsheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if ( buttonIndex != 0 ) return;
    
	//删除联系人
    NSInteger row = actionSheet.tag;
    User* user = [friends objectAtIndex:row];
    [self didDelete:user.userId];
}



/*
- (void)searchBarSearchButtonClicked:(UISearchBar *)sb
{
	NSLog(@"111search text = %@", sb.text );
	[searchBar resignFirstResponder];
}


- (void)searchBarCancelButtonClicked:(UISearchBar *)sb
{
	NSLog(@"cancel");
	[sb resignFirstResponder];
}
*/


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
 */


/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [friends count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"GroupUserListCell";
    
    ProfileImageCell *cell = (ProfileImageCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
		cell = [[[ProfileImageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

	User* friend = [friends objectAtIndex:indexPath.row];
	NSString* profileImage = friend.profileImageUrl_s;
    cell.imageView.image = [cell getProfileImage:profileImage isLarge:NO];
	cell.textLabel.text = friend.screenName;
    
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"row_delete.png"] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 44, 44);
    button.tag = indexPath.row;
    [button addTarget:self action:@selector(delete:) forControlEvents:UIControlEventTouchUpInside];
    cell.accessoryView = button;
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSInteger row = indexPath.row;
	User* user = [friends objectAtIndex:row];
	[friends removeObjectAtIndex:row];
	[deletedFriends addObject:user];
	
    NSInteger index = -1;
    for ( int i=0; i<[group.friends count]; i++ ) {
        User* u = [group.friends objectAtIndex:i];
        if ( u.userId == user.userId ) {
            index = i;
            break;
        }
    }
    
    if ( index >=0 ) {
        [group.friends removeObjectAtIndex:index];
        group.friendCount = [group.friends count];
    }
    
    [self.tableView reloadData];
	
    [GroupService removeUser:user.userId fromGroup:group.groupId];
}


- (NSIndexPath*) tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}



#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload 
{
	[friends release];
	[group release];
	[deletedFriends release];
	[addedFriends release];
	//[searchBar release];
}


- (void)dealloc {
	[friends release];
	[group release];
	[deletedFriends release];
	[addedFriends release];
	//[searchBar release];
    [super dealloc];
}


@end

